package ModelLayer;
/**
 * This CustomerContainer reads customer input. It returns the customer
 * as an object of class Customer.
 * @author frankeskelund
 *
 */

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import ModelLayer.Enums.CustomerType;
import ModelLayer.FileHandlers.CustomerFileHandler;

public class CustomerContainer 
{
	/**
	 * This is singleton for the CustomerContainer
	 */
	private static CustomerContainer instance;

	private CustomerContainer()
	{
		fileHandler = new CustomerFileHandler("customers");
	}

	private CustomerFileHandler fileHandler;
	
	/**
	 * get instance of CustomerContainer
	 * @return CustomerContainer instance object
	 */
	public static CustomerContainer getInstance()
	{
		if(instance == null)
		{
			instance = new CustomerContainer();
		}
		
		return instance;
	}
	
	/**
	 * Add customer to a file
	 * @param c insert filled customer object
	 */
	public void addCustomer(Customer c)
	{
		fileHandler.add(c);
	}
	
	/**
	 * Remove customer based on same phonenumber in the object
	 * @param Insert customer object with phonenumber
	 * @return true if custoemr was found in the file and removed
	 */
	public boolean removeCustomer(Customer c)
	{
		ArrayList<Customer> customers = fileHandler.getAll();
		
		Iterator<Customer> iterator = customers.iterator();
		boolean found = false;
		
		while(iterator.hasNext() && !found)
		{
			Customer nextCustomer = iterator.next();
			if (nextCustomer.getPhoneNumber().equals(c.getPhoneNumber())) {
				found = true;
				customers.remove(nextCustomer);
			}
		}
			
		return found;
	}
	
	/**
	 * Finds the matching customer
	 * @param phoneNumber
	 * @return The found customer, or null if no matches
	 */
	public Customer findCustomer(String phoneNumber, CustomerType customerType)
	{
		ArrayList<Customer> customers = fileHandler.getAll();
		Iterator<Customer> iterator = customers.iterator();
		
		while(iterator.hasNext())
		{
			Customer nextCustomer = iterator.next();
			if(nextCustomer.getPhoneNumber().equals(phoneNumber) && nextCustomer.getCustomerType().equals(customerType)){
				return nextCustomer;
			}
		}
		
		return null;
	}
	
	/**
	 * Adds dummy customers in the system for test
	 */
	public void addDummyCustomers()
	{
		if(fileHandler.getAll().isEmpty())
		{
			fileHandler.add(new Customer(CustomerType.PRIVATE, "Tobias", "Beddingen 9", "53616797", "tobiaskastrupandersen@gmail.com", new Date().toString()));
		}
	}

}
